<?php
/**
 * | 节程 [ 节程赋能开发者，助力企业发展 ]
 * +----------------------------------------------------------------------
 *  | Copyright (c) 2020~2029 温州惊蛰网络科技有限公司 All rights reserved.
 * +----------------------------------------------------------------------
 *  | Licensed 节程并不是自由软件，未经许可不能去掉节程相关版权
 * +----------------------------------------------------------------------
 */


namespace app\index\controller;

use app\BaseController;
use app\index\model\Configuration;
use app\index\service\ServiceFactory;
use think\App;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use \think\facade\Request;

class Login extends BaseAction
{
    private $appId;
    private $appSecret;
    private $type;

    public function __construct(App $app)
    {
        parent::__construct($app);
    }


    public function login()
    {
        $param = input('post.code');
        $url = input('post.url');
        $pid = input('post.pid', null);
        $type = Request::header('UserType');//带user_type 1.小程序 2.公众号
        $res = ServiceFactory::getResult('SourceService', 'judge', $type);
        $this->type = $type;
        $this->appId = $res['appid'];
        $this->appSecret = $res['appsecret'];
        switch ($this->type) {
            case 1:
                return $this->getUserInfo($param, $pid);
            case 2:
                return $this->getBaseInfo($url);
            default:
                throw new \Exception('错误请求,请稍后再试...!');

        }
    }

    public function getBaseInfo($url)
    {
        $mid = $this->handleUrl($url);
        $redirect_uri = urlencode(Request::domain() . "/index/login/getUserOpenId?mall_id=" . $mid);
        $this->appId = empty($this->appId) ?
            json_decode(Db::name('configuration')
                ->where('mall_id',$mid)
                ->where('type','wx')
                ->value('configuration'),true)
                ['appid'] : $this->appId;
        $key = uniqid();
        Cache::store('redis')->set("LOGIN:" . $key, $url, 60 * 60 * 24);
        $url1 = urlencode($key);
        $url = Url::$LOCAL_URL . "appid=" . $this->appId . "&redirect_uri=" . $redirect_uri . "&response_type=code&scope=snsapi_userinfo&state=" . $url1 . "&connect_redirect=1#wechat_redirect";
        ob_clean();
        header('location:'.$url);
        exit();
    }

    public function getUserOpenId()
    {
        global $mid;
        $codeWx = $_GET['code'];
        $res = Configuration::where('type', 'wx')
            ->where('mall_id', $mid)
            ->field('configuration')
            ->find();
        $js = json_decode($res, true)['configuration'];
        $access = Url::$ACCESS_TOKEN . "appid=" . trim($js['appid']) . "&secret=" . trim($js['appsecret']) . "&code=" . trim($codeWx) . "&grant_type=authorization_code";
        $access_token = json_decode(http_curl($access), true);

        $url1 = Cache::store('redis')->get("LOGIN:" . urldecode($_GET['state']));
        if ($url1 == null) {
            $url = $this->curPageURL();
            $url1 = $url."/h5/#/pages/mine/mine?mall_id=".$_GET['mall_id'];
        }
        list($jump_url, $arr) = $this->division($url1);
        $data = $access_token;
        $data['mid'] = $mid;
        $data = array_merge($data, $arr);
        list($code, $msg) = ServiceFactory::getResult(class_basename($this) . 'Service', __FUNCTION__, $data, $js);
        if ($code = '200')
            cookie("token", $msg, 30);
        else
            throw new Exception('请重新登录...', HTTP_UNAUTH);
        header('location:' . $jump_url);
    }

    function curPageURL()
    {
        $pageURL = 'http';

        if ($_SERVER["HTTPS"] == "on")
        {
            $pageURL .= "s";
        }
        $pageURL .= "://";

        if ($_SERVER["SERVER_PORT"] != "80")
        {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] ;
        }
        else
        {
            $pageURL .= $_SERVER["SERVER_NAME"] ;
        }
        return $pageURL;
    }

    public function getUserInfo(string $code, string $pid = null)
    {
        $url = Url::$CODE_URL . "appid=" . trim($this->appId) . "&secret=" . trim($this->appSecret) . "&js_code=" . trim($code) . "&grant_type=authorization_code";
        $data = http_curl($url);
        $js = json_decode($data, true);
        if (isset($js['errcode'])) {
            throw new Exception("发生错误，请重试！", HTTP_NOTACCEPT);
        }
        $js['mid'] = request()->header('mid');
        list($code, $msg) = ServiceFactory::getResult(class_basename($this) . 'Service', __FUNCTION__, $js, $pid);
        return json(['msg' => $msg], $code);
    }

    public function saveUserInfo()
    {
        $post = input('post.');
        $post['mid'] = request()->header('mid');
        list($code, $msg) = ServiceFactory::getResult(class_basename($this) . 'Service', __FUNCTION__, $post);
        return json(['msg' => $msg], $code);
    }


    public function getTokenUser()
    {
        $get = input('get.');
        list($code, $msg) = ServiceFactory::getResult(class_basename($this) . 'Service', __FUNCTION__, $get['token']);
        return json(['msg' => $msg], $code);
    }


    public function getSmsCode()
    {
        $phone = input('phone');
        list($code, $result) = ServiceFactory::getResult('LoginService', 'getSmsCode', $phone);
        return json(['msg' => $result], $code);
    }

    public function getPhone()
    {
        $data = input('post.');
        list($code, $msg) = ServiceFactory::getResult(class_basename($this) . 'Service', __FUNCTION__, $data['code'], $data['user_id']);
        return json(['msg' => $msg], $code);
    }

    public function verificationSmsCode(string $phone, string $code)
    {
        list($code, $result) = ServiceFactory::getResult('LoginService', 'verificationSmsCode', $phone, $code);
        return json(['msg' => $result], $code);
    }


    public function getUserPhone()
    {
        $data = input('post.');
        list($code, $result) = ServiceFactory::getResult('LoginService', __FUNCTION__, $data);
        return json(['msg' => $result], $code);
    }

    public function text()
    {
        $str = "24fe7900cc0417e0d32d758f875170dbc8d53ea4";
        $res = Cache::store('redis')->get('INDEX:' . $str . "-4236");
        $res1 = Cache::store('redis')->get('INDEX:' . $str . "-82697");
    }

    public function division(string $url1)
    {
        $data = [];
        $param = "";
        if (strrpos($url1, "?")) {
            $str = explode("&", substr($url1, strrpos($url1, "?") + 1));
            foreach ($str as $v) {
                $arr = explode("=", $v);
                if (in_array($arr[0], ['pid', 'mid'])) {
                    if ($arr[0] == 'pid') $data['pid'] = $arr[1];
                    if ($arr[0] == 'mid') $data['mid'] = $arr[1];
                } else {
                    $param .= $v . "&";
                }
            }
        }
        $jump_url = !strrpos($url1, "?") ? $url1 : substr($url1, 0, strrpos($url1, "?")) . '?' . trim($param, "&");
        return [$jump_url, $data];
    }

    private function handleUrl(string $url)
    {
        $str = substr($url, strrpos($url, "?") + 1);
        $mid = '';
        if (strrpos($str, '&')) {
            $arr = explode("&", $str);
            foreach ($arr as $v) {
                $v_arr = explode('=', $v);
                if (in_array('mall_id', $v_arr))
                    $mid = $v_arr[1];
            }
        } else {
            $arr = explode('=', $str);
            $mid = $arr[1];
        }
        return $mid;
    }

    public function refresh_token(string $appid, string $refresh_token)
    {
        $res = Url::$REFRRESH_TOKEN . "appid=" . $appid . "&grant_type=refresh_token&refresh_token=" . $refresh_token;
        return http_curl($res);
    }
}